<?php
/**
 * R
 * 格式化返回
 * @package haoleke-framework
 * @author GXH <gexiuhua@live.com>
 * @copyright Copyright (c) 2025 云想科技
 * @license MIT
 * @version 1.0.0
 * @created 2025/3/27
 */

namespace haoleke\utils;

use think\Response;
class R
{
    /**
     * 错误返回
     * @param $msg
     * @param $code
     * @param $status
     * @return mixed
     */
    public static function error($msg = '', $code = 1,$status = 200)
    {
        $json = self::make($code,$msg ?:'操作失败');
        return Response::create($json, 'json', $status);
    }

    /**
     * 成功返回
     * @param $data
     * @param int $count
     * @param $ext
     * @return mixed
     */
    public static function success($data = null, int $count = 0, $ext = null)
    {
        if(!is_array($data) && !is_object($data) && !empty($data)){
            $json = self::make(0, $data, [] ,$count ,$ext);
        }else{
            $json = self::make(0,'操作成功!',$data ,$count ,$ext);
        }
        return Response::create($json, 'json');
    }

    /**
     * 格式化返回
     * @param $code
     * @param $msg
     * @param $data
     * @param $count
     * @param $ext
     * @return array
     */
    public static function make($code = 0, $msg = '',$data = null, $count = 0, $ext = [])
    {
        $data = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
            'count' => $count
        ];
        // 扩展参数不为空，则合并数组
        if(!empty($ext) && count($ext) > 0){
            $data = array_merge($data,$ext);
        }
        return $data;
    }
}